import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  const userId = ref(localStorage.getItem('userId') || '')

  const adminPrivilege = ref(localStorage.getItem('admin') || 0)

  const userInfoList = ref(JSON.parse(localStorage.getItem('user_info_list')) || [])

  const filterUserInfo = computed(() =>
    userInfoList.value.find(item => item.userId === userId.value)
  )

  const defaultUserInfo = {
    name: '神秘又神秘66',
    email: '',
    phone: null,
    sex: 'secret',
    address: ''
  }

  const userInfo = ref(filterUserInfo.value || defaultUserInfo)

  const saveToLocal = () => {
    localStorage.setItem('user_info_list', JSON.stringify(userInfoList.value))
  }

  const setUserInfo = _userInfo => {
    userInfo.value = _userInfo
    userInfo.value.userId = userId.value
    const result = userInfoList.value.find(item => item.userId === userId.value)
    if (result) {
      Object.assign(result, _userInfo)
    } else {
      userInfoList.value.push(userInfo.value)
    }
    saveToLocal()
  }

  const setUserAddress = address => {
    const result = userInfoList.value.find(item => item.userId === userId.value)
    if (result) {
      result.address = address
    } else {
      setUserInfo(defaultUserInfo)
      const result = userInfoList.value.find(item => item.userId === userId.value)
      result.address = address
    }
    userInfo.value.address = address
    saveToLocal()
  }

  const setUserId = _userId => {
    userId.value = _userId
    userInfo.value = filterUserInfo.value || defaultUserInfo
    localStorage.setItem('userId', userId.value)
    saveToLocal()
  }

  const setAdmin = _userId => {
    setUserId(_userId)
    adminPrivilege.value = 1
    localStorage.setItem('admin', adminPrivilege.value)
  }

  const clearUserInfo = () => {
    userId.value = ''
    adminPrivilege.value = 0
    userInfo.value = filterUserInfo.value || defaultUserInfo
    localStorage.removeItem('userId')
    localStorage.removeItem('admin')
  }

  return {
    userId,
    userInfo,
    adminPrivilege,
    setUserInfo,
    setUserId,
    clearUserInfo,
    setUserAddress,
    setAdmin
  }
})
